package com.miandian.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.miandian.common.JwtUtil;
import com.miandian.common.R;
import com.miandian.common.UserBean;
import com.miandian.entities.Menu;
import com.miandian.entities.User;
import com.miandian.service.MenuService;
import com.miandian.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.protocol.ResponseDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api")
@Api(value = "用户管理",tags = "用户管理")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private MenuService menuService;

    @ApiOperation(value = "用户登录",httpMethod = "POST",response = ResponseDate.class, notes = "用户登录")
    @PostMapping("/login")
    public R login(HttpServletRequest request,@RequestBody User user){
        String password = user.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,user.getUsername());
        User use = userService.getOne(queryWrapper);

        if(use == null){
            return  R.error("登陆失败");
        }
        //比对密码
        log.info(use.getPassword());
        if (!use.getPassword().equals(password)){
            return R.error("登陆失败");
        }
        //产看有用户状态
        if (use.getStatus()==0){
            return R.error("账号已禁用");
        }
        request.getSession().setAttribute("user",use.getId());
        String token = jwtUtil.createToken(use.getId(),use.getUsername(),use.getIsManager());
        log.info(token);
        UserBean userBean = new UserBean(token,use);
        return R.success(userBean);
    }

    /**
     * 推出登录
     * @param request
     * @return
     */
    @PostMapping("/logout")
    @ApiOperation(value = "退出登录",httpMethod = "POST",response = ResponseDate.class, notes = "退出登录")
    public R logOut(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        System.out.println("推出登录");
        return null;
    }
    /**
     * 注册账号
     */
    @PostMapping("/regist")
    @ApiOperation(value = "注册",httpMethod = "POST",response = ResponseDate.class, notes = "用户注册")
    public R regist(HttpServletRequest request, @RequestBody User user){
//        Page pageInfo = new Page(1,1);
        Page pageInfo = new Page(1,10);
        //判断用户名是否已经注册了
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
        //添加过滤条件
        queryWrapper.eq(StringUtils.isNotBlank(user.getUsername()),User::getUsername,user.getUsername());
        //排序
        queryWrapper.orderByDesc(User::getCreateTime);
        //执行查询
//        userService.page(pageInfo,queryWrapper);
        userService.page(pageInfo,queryWrapper);
        if(pageInfo.getRecords().size()>0){
            return R.error("用户已存在");
        }
        //密码加密
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        user.setStatus(1);
        user.setIsManager(1);
        userService.save(user);
//        获取一下token解析是谁创建的
        return R.success("注册成功");
    }
    //获取用户权限
    @ApiOperation(value = "获取用户信息",httpMethod = "GET",response = ResponseDate.class, notes = "获取用户信息")
    @GetMapping("/menu")
    public R userInfo(HttpServletRequest request){
        String token = request.getHeader("token");
        Map obj = jwtUtil.parseJwt(token);
        Integer i = (Integer) obj.get("isManager");
        if(i==1){
            Page pageInfo = new Page(1,100);
            //判断用户名是否已经注册了
            LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper();
            //添加过滤条件
//            queryWrapper.eq(StringUtils.isNotBlank(),User::getUsername,user.getUsername());
            menuService.page(pageInfo,queryWrapper);
            return R.success(pageInfo.getRecords());
        }else {
            return R.error("暂时无权限");
        }
    }

    @GetMapping("/user/getList")
    public R getList(@RequestParam(defaultValue = "1") Integer page,
                     @RequestParam(defaultValue = "10") Integer pageSize,
                     String username){
        Page pageInfo = new Page(page,pageSize);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.like(StringUtils.isNotBlank(username),User::getUsername,username);
        queryWrapper.orderByDesc(User::getCreateTime);
        userService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }

}
